import 'dart:async';
import 'package:flutter/material.dart';
import 'package:native_video_cache/native_video_cache.dart';

/// 缓存功能演示页面
///
/// 这个页面展示了 Native AV 插件的所有缓存相关功能：
/// - 缓存初始化和配置
/// - 视频缓存的开始、停止、清理
/// - 缓存状态监听和进度显示
/// - 代理URL获取
/// - 缓存信息查询
class CacheDemo extends StatefulWidget {
  const CacheDemo({super.key});

  @override
  State<CacheDemo> createState() => _CacheDemoState();
}

class _CacheDemoState extends State<CacheDemo> {
  bool _isInitialized = false;
  String _status = '未初始化';
  Timer? _refreshTimer;
  bool _isClearingCache = false;
  DateTime? _lastGlobalClearTime;
  final List<VideoItem> _videos = [
    VideoItem(
      title: '示例视频 1',
      url:
          'https://new-jp.oss-cn-hangzhou.aliyuncs.com/jp_video/%E7%A7%91%E4%B8%802.2.2%E7%A6%81%E4%BB%A4%E6%A0%87%E5%BF%97.mp4',
    ),
    VideoItem(
      title: '示例视频 2',
      url:
          'https://new-jp.oss-cn-hangzhou.aliyuncs.com/jp_video/%E7%A7%91%E4%B8%802.1.1%E4%BA%A4%E9%80%9A%E4%BF%A1%E5%8F%B7%E7%81%AF%E7%9A%84%E5%88%86%E7%B1%BB%E3%80%81%E6%9C%BA%E5%8A%A8%E8%BD%A6%E5%92%8C%E9%9D%9E%E6%9C%BA%E5%8A%A8%E8%BD%A6%E4%BF%A1%E5%8F%B7%E7%81%AF.mp4',
    ),
    VideoItem(
      title: '示例视频 3',
      url:
          'https://new-jp.oss-cn-hangzhou.aliyuncs.com/jp_video/%E7%A7%91%E4%B8%802.2.5%E6%97%85%E6%B8%B8%E5%8C%BA%E3%80%81%E4%BD%9C%E4%B8%9A%E5%8C%BA%E3%80%81%E5%91%8A%E7%A4%BA%E3%80%81%E8%BE%85%E5%8A%A9%E6%A0%87%E5%BF%97.mp4',
    ),
  ];

  @override
  void initState() {
    super.initState();
    _initializeCache();
  }

  @override
  void dispose() {
    NativeVideoCacheManager.dispose();
    super.dispose();
  }

  Future<void> _initializeCache() async {
    try {
      setState(() {
        _status = '正在初始化...';
      });

      await NativeVideoCacheManager.initialize(
        CacheConfig(
          maxCacheSize: 500 * 1024 * 1024, // 500MB
          maxConcurrentDownloads: 2,
          connectTimeout: 30000,
          readTimeout: 30000,
        ),
      );

      // 添加全局监听器
      NativeVideoCacheManager.addProgressListener((url, progress) {
        debugPrint('缓存进度: $url -> ${(progress * 100).toStringAsFixed(1)}%');
        _updateVideoProgress(url, progress);
      });

      NativeVideoCacheManager.addStatusListener((url, status) {
        debugPrint('缓存状态: $url -> $status');
        _updateVideoStatus(url, status);
      });

      NativeVideoCacheManager.addErrorListener((url, error) {
        debugPrint('缓存错误: $url -> $error');
      });

      setState(() {
        _isInitialized = true;
        _status = '初始化成功';
      });
    } catch (e) {
      setState(() {
        _status = '初始化失败: $e';
      });
    }
  }

  void _updateVideoProgress(String url, double progress) {
    if (_isClearingCache) return;

    setState(() {
      for (var video in _videos) {
        if (video.url == url) {
          video.cacheInfo = video.cacheInfo?.copyWith(progress: progress) ??
              CacheInfo(
                originalUrl: url,
                status: CacheStatus.caching,
                progress: progress,
                cachedSize: 0,
                totalSize: 0,
                errorMessage: null,
              );
          break;
        }
      }
    });
  }

  void _updateVideoStatus(String url, CacheStatus status) {
    if (_isClearingCache) return;

    setState(() {
      for (var video in _videos) {
        if (video.url == url) {
          video.cacheInfo = video.cacheInfo?.copyWith(status: status) ??
              CacheInfo(
                originalUrl: url,
                status: status,
                progress: 0.0,
                cachedSize: 0,
                totalSize: 0,
                errorMessage: null,
              );
          break;
        }
      }
    });
  }

  Future<void> _refreshAllVideosStatus() async {
    for (var video in _videos) {
      try {
        final info = await NativeVideoCacheManager.getCacheInfo(video.url);

        debugPrint(
            '全局刷新获取状态: ${info?.status} - ${video.title}, cachedSize: ${info?.cachedSize ?? 0}');

        // 直接更新状态
        if (mounted) {
          setState(() {
            video.cacheInfo = info;
          });
        }
      } catch (e) {
        // 忽略获取缓存信息的错误
        debugPrint('全局刷新获取状态失败 - ${video.title}: $e');
        // 如果获取状态失败，将UI状态设为未知或null
        if (mounted) {
          setState(() {
            video.cacheInfo = null;
          });
        }
      }
    }
  }

  Future<void> _getCacheInfo() async {
    if (!_isInitialized) return;

    try {
      final totalSize = await NativeVideoCacheManager.getTotalCacheSize();
      final formattedSize = NativeVideoCacheManager.formatFileSize(totalSize);

      setState(() {
        _status = '总缓存大小: $formattedSize';
      });
    } catch (e) {
      setState(() {
        _status = '获取缓存信息失败: $e';
      });
    }
  }

  Future<void> _clearAllCache() async {
    if (!_isInitialized) return;

    try {
      // 设置清理状态标记，防止监听器干扰
      setState(() {
        _isClearingCache = true;
        _status = '正在清理所有缓存...';
      });

      // 停止自动刷新，避免干扰
      _refreshTimer?.cancel();

      // 立即清空所有视频状态
      for (var video in _videos) {
        video.cacheInfo = null;
        video.proxyUrl = null;
      }
      _lastGlobalClearTime = DateTime.now(); // 记录全局清理时间

      // 执行native清理
      await NativeVideoCacheManager.clearAllCache();

      setState(() {
        _status = '缓存已清理，等待状态同步...';
      });

      // 等待更长时间确保native端完全清理
      await Future.delayed(const Duration(milliseconds: 4000));

      // 清除清理状态标记，重新启用监听器
      setState(() {
        _isClearingCache = false;
        _status = '正在验证清理结果...';
      });

      // 验证每个视频的清理结果
      for (var video in _videos) {
        try {
          final info = await NativeVideoCacheManager.getCacheInfo(video.url);

          debugPrint('全局清理后获取状态: ${info?.status} - ${video.title}');
          debugPrint('缓存大小: ${info?.cachedSize ?? 0} bytes');
          debugPrint('总大小: ${info?.totalSize ?? 0} bytes');

          // 只有当native确实返回none状态时，才更新状态
          if (info != null &&
              info.status == CacheStatus.none &&
              info.cachedSize == 0) {
            video.cacheInfo = info;
            debugPrint('视频 ${video.title} 状态验证通过');
          } else {
            // 如果native还返回其他状态，强制保持清空状态
            video.cacheInfo = null;
            debugPrint('视频 ${video.title} 清理后native状态未同步，强制保持清空状态');
            debugPrint(
                '原因: status=${info?.status}, cachedSize=${info?.cachedSize}');
          }
        } catch (e) {
          // 如果获取状态出错，保持null状态
          video.cacheInfo = null;
          debugPrint('获取视频 ${video.title} 清理后状态失败: $e');
        }
      }

      // 强制重新获取缓存信息
      await _getCacheInfo();

      setState(() {
        _status = '缓存清理完成，状态已同步';
      });
    } catch (e) {
      setState(() {
        _isClearingCache = false; // 确保错误时也清除标记
        _status = '清理缓存失败: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('缓存功能演示'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 状态显示
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text(
                          '缓存状态',
                          style: Theme.of(context).textTheme.titleMedium,
                        ),
                        const Spacer(),
                        if (_refreshTimer?.isActive == true)
                          Row(
                            children: [
                              const SizedBox(
                                width: 12,
                                height: 12,
                                child:
                                    CircularProgressIndicator(strokeWidth: 2),
                              ),
                              const SizedBox(width: 8),
                              Text(
                                '自动刷新中',
                                style: Theme.of(context).textTheme.bodySmall,
                              ),
                            ],
                          )
                        else
                          Text(
                            '手动模式',
                            style: Theme.of(context).textTheme.bodySmall,
                          ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Text(_status),
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        ElevatedButton(
                          onPressed: _isInitialized ? _getCacheInfo : null,
                          child: const Text('获取缓存信息'),
                        ),
                        const SizedBox(width: 8),
                        ElevatedButton(
                          onPressed: _isInitialized ? _clearAllCache : null,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.red,
                            foregroundColor: Colors.white,
                          ),
                          child: const Text('清理所有缓存'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 视频列表
            Text(
              '视频列表',
              style: Theme.of(context).textTheme.titleMedium,
            ),
            const SizedBox(height: 8),
            Expanded(
              child: ListView.builder(
                itemCount: _videos.length,
                itemBuilder: (context, index) {
                  return VideoItemWidget(
                    video: _videos[index],
                    isInitialized: _isInitialized,
                    onStatusChanged: () => setState(() {}),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class VideoItem {
  final String title;
  final String url;
  CacheInfo? cacheInfo;
  String? proxyUrl;

  VideoItem({
    required this.title,
    required this.url,
    this.cacheInfo,
    this.proxyUrl,
  });
}

extension CacheInfoCopy on CacheInfo {
  CacheInfo copyWith({
    String? originalUrl,
    CacheStatus? status,
    double? progress,
    int? cachedSize,
    int? totalSize,
    String? errorMessage,
  }) {
    return CacheInfo(
      originalUrl: originalUrl ?? this.originalUrl,
      status: status ?? this.status,
      progress: progress ?? this.progress,
      cachedSize: cachedSize ?? this.cachedSize,
      totalSize: totalSize ?? this.totalSize,
      errorMessage: errorMessage ?? this.errorMessage,
    );
  }
}

class VideoItemWidget extends StatefulWidget {
  final VideoItem video;
  final bool isInitialized;
  final VoidCallback onStatusChanged;

  const VideoItemWidget({
    super.key,
    required this.video,
    required this.isInitialized,
    required this.onStatusChanged,
  });

  @override
  State<VideoItemWidget> createState() => _VideoItemWidgetState();
}

class _VideoItemWidgetState extends State<VideoItemWidget> {
  bool _isLoading = false;
  bool _isClearing = false;

  @override
  void initState() {
    super.initState();
    _updateCacheInfo();
  }

  Future<void> _getProxyUrl() async {
    if (!widget.isInitialized) return;

    setState(() {
      _isLoading = true;
    });

    try {
      final proxyUrl = await NativeVideoCacheManager.getProxyUrl(widget.video.url);
      widget.video.proxyUrl = proxyUrl;
      widget.onStatusChanged();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('获取代理URL失败: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _startCache() async {
    if (!widget.isInitialized) return;

    setState(() {
      _isLoading = true;
    });

    try {
      await NativeVideoCacheManager.startCache(widget.video.url);
      _updateCacheInfo();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('开始缓存失败: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _stopCache() async {
    if (!widget.isInitialized) return;

    try {
      await NativeVideoCacheManager.stopCache(widget.video.url);
      _updateCacheInfo();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('停止缓存失败: $e')),
        );
      }
    }
  }

  Future<void> _clearCache() async {
    if (!widget.isInitialized) return;

    try {
      setState(() {
        _isClearing = true;
      });

      // 执行native清理
      await NativeVideoCacheManager.clearCache(widget.video.url);

      // 清理成功后，直接清空本地状态并刷新UI
      widget.video.cacheInfo = CacheInfo(
        originalUrl: widget.video.url,
        status: CacheStatus.none,
        progress: 0.0,
        cachedSize: 0,
        totalSize: 0,
        errorMessage: null,
      );
      widget.video.proxyUrl = null;
      widget.onStatusChanged(); // 通知父组件刷新列表
      setState(() {}); // 刷新当前VideoItemWidget

      setState(() {
        _isClearing = false;
      });
    } catch (e) {
      setState(() {
        _isClearing = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('清理缓存失败: $e')),
        );
      }
    }
  }

  Future<void> _updateCacheInfo() async {
    if (!widget.isInitialized) return; // 不再检查_isClearing，因为清理后会直接设置状态

    try {
      final info = await NativeVideoCacheManager.getCacheInfo(widget.video.url);

      debugPrint(
          '手动刷新/初始化获取状态: ${info?.status} - ${widget.video.title}, cachedSize: ${info?.cachedSize ?? 0}');

      // 直接更新状态
      widget.video.cacheInfo = info;
      setState(() {});
      widget.onStatusChanged();

      debugPrint('状态已更新到UI');
    } catch (e) {
      debugPrint('更新缓存信息失败: $e');
      // 获取失败时，将UI状态设为未知或null
      if (mounted) {
        setState(() {
          widget.video.cacheInfo = null;
        });
      }
    }
  }

  String _getStatusText() {
    final info = widget.video.cacheInfo;
    if (info == null) return '未缓存';

    switch (info.status) {
      case CacheStatus.none:
        return '未缓存';
      case CacheStatus.caching:
        return '缓存中 ${(info.progress * 100).toStringAsFixed(1)}%';
      case CacheStatus.cached:
        return '已缓存';
      case CacheStatus.error:
        return '缓存错误';
    }
  }

  Color _getStatusColor() {
    final info = widget.video.cacheInfo;
    if (info == null) return Colors.grey;

    switch (info.status) {
      case CacheStatus.none:
        return Colors.grey;
      case CacheStatus.caching:
        return Colors.orange;
      case CacheStatus.cached:
        return Colors.green;
      case CacheStatus.error:
        return Colors.red;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              widget.video.title,
              style: Theme.of(context).textTheme.titleSmall,
            ),
            const SizedBox(height: 4),
            Text(
              widget.video.url,
              style: Theme.of(context).textTheme.bodySmall,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            const SizedBox(height: 8),

            // 状态显示
            Row(
              children: [
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: _getStatusColor().withOpacity(0.2),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    _getStatusText(),
                    style: TextStyle(
                      color: _getStatusColor(),
                      fontSize: 12,
                    ),
                  ),
                ),
                if (widget.video.cacheInfo != null) ...[
                  const SizedBox(width: 8),
                  Text(
                    '${NativeVideoCacheManager.formatFileSize(widget.video.cacheInfo!.cachedSize)}',
                    style: Theme.of(context).textTheme.bodySmall,
                  ),
                  if (widget.video.cacheInfo!.totalSize > 0) ...[
                    Text(
                      ' / ${NativeVideoCacheManager.formatFileSize(widget.video.cacheInfo!.totalSize)}',
                      style: Theme.of(context).textTheme.bodySmall,
                    ),
                  ],
                ],
              ],
            ),

            // 进度条
            if (widget.video.cacheInfo?.status == CacheStatus.caching) ...[
              const SizedBox(height: 8),
              LinearProgressIndicator(
                value: widget.video.cacheInfo!.progress,
                backgroundColor: Colors.grey[300],
                valueColor: const AlwaysStoppedAnimation<Color>(Colors.orange),
              ),
            ],

            const SizedBox(height: 12),

            // 操作按钮
            Wrap(
              spacing: 8,
              children: [
                ElevatedButton(
                  onPressed: widget.isInitialized && !_isLoading && !_isClearing
                      ? _getProxyUrl
                      : null,
                  child: _isLoading
                      ? const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        )
                      : const Text('获取代理URL'),
                ),
                ElevatedButton(
                  onPressed: widget.isInitialized && !_isLoading && !_isClearing
                      ? _startCache
                      : null,
                  child: const Text('开始缓存'),
                ),
                ElevatedButton(
                  onPressed:
                      widget.isInitialized && !_isClearing ? _stopCache : null,
                  child: const Text('停止缓存'),
                ),
                ElevatedButton(
                  onPressed:
                      widget.isInitialized && !_isClearing ? _clearCache : null,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red,
                    foregroundColor: Colors.white,
                  ),
                  child: _isClearing
                      ? const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor:
                                AlwaysStoppedAnimation<Color>(Colors.white),
                          ),
                        )
                      : const Text('清理'),
                ),
              ],
            ),

            // 代理URL显示
            if (widget.video.proxyUrl != null) ...[
              const SizedBox(height: 8),
              Text(
                '代理URL: ${widget.video.proxyUrl}',
                style: Theme.of(context).textTheme.bodySmall,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ],
        ),
      ),
    );
  }
}
